/**
 * 
 */
package com.agilegroup.crm.ui.fragments;

import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.agilegroup.crm.AgileApplication;
import com.agilegroup.crm.R;
import com.agilegroup.crm.adapters.LeadAdapter;
import com.agilegroup.crm.model.LeadData;
import com.agilegroup.crm.model.LeadList;
import com.agilegroup.crm.requests.LeadsJsonRequest;
import com.agilegroup.crm.ui.ListDialogActivity;
import com.agilegroup.crm.ui.NewLeadActivity;
import com.agilegroup.crm.ui.ViewLeadActivity;
import com.agilegroup.crm.utils.OnlineChecker;
import com.agilegroup.crm.utils.SessionManager;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;

/**
 * @author Hisham
 *
 */
public class LeadFragment extends SherlockListFragment{

	private SessionManager sessionManager;
	private static final String JSON_CACHE_KEY = "leads_json";
	private OnlineChecker checker;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        
        
        return super.onCreateView(inflater, container, savedInstanceState);
    }
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	// TODO Auto-generated method stub
    	super.onCreate(savedInstanceState);
    	setRetainInstance(true);
    	checker = new OnlineChecker(getActivity());
    }
    @SuppressWarnings("static-access")
	@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    	// TODO Auto-generated method stub
    	super.onViewCreated(view, savedInstanceState);
    	setHasOptionsMenu(true);
    	sessionManager = new SessionManager(getSherlockActivity());    
    	HashMap<String, String> user = sessionManager.getUserDetails();
    	String empId = user.get(sessionManager.KEY_ID);
    	AgileApplication.getInstance().spiceManager.execute(new LeadsJsonRequest(empId),
    			JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new LeadListJsonRequestListener());
    }
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	TextView leadId = (TextView)v.findViewById(R.id.txtid);
    	if(checker.isOnline()==true){
    		Intent view = new Intent(this.getSherlockActivity(),ViewLeadActivity.class);
    		view.putExtra("leadId", leadId.getText().toString());
        	getSherlockActivity().startActivity(view);
    	}
    	else{
    		SherlockDialogFragment dialogFragment = new ConnectionDialogFragment();
			dialogFragment.show(getSherlockActivity().getSupportFragmentManager(), "connectionDialog");
    	}
    	
    }
    
    public class LeadListJsonRequestListener implements RequestListener<LeadList>{

		public void onRequestFailure(SpiceException spiceException) {
			Toast.makeText(LeadFragment.this.getSherlockActivity(), "Failure", Toast.LENGTH_SHORT).show();
		}
		public void onRequestSuccess(LeadList result) {
			List<LeadData>leadData = result.getLeadData();
			if (leadData.size()==0) {
				setEmptyText(getResources().getString(R.string.no_data));
			}
			LeadAdapter adapter = new LeadAdapter(LeadFragment.this.getSherlockActivity(), leadData);
			Log.d(LeadFragment.class.getSimpleName(), "success");
			setListAdapter(adapter);
			//Toast.makeText(LeadFragment.this.getSherlockActivity(), "Success", Toast.LENGTH_SHORT).show();
		}
	 }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    	super.onActivityCreated(savedInstanceState);
    	
    	OnItemLongClickListener longClickListener = new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Intent listDialog = new Intent(LeadFragment.this.getSherlockActivity(),ListDialogActivity.class);
				TextView leadId = (TextView)arg1.findViewById(R.id.txtid);
				TextView email = (TextView)arg1.findViewById(R.id.txtEmail);
				TextView mobile = (TextView)arg1.findViewById(R.id.txtMobile);
				
				listDialog.putExtra("listDialog", "1");
				listDialog.putExtra("leadId", leadId.getText().toString());
				listDialog.putExtra("email", email.getText().toString());
				listDialog.putExtra("mobile", mobile.getText().toString());
				LeadFragment.this.getSherlockActivity().startActivity(listDialog);
				return false;
			}
		};
		getListView().setOnItemLongClickListener(longClickListener);
    }
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.leads_menu, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}
	@SuppressWarnings("static-access")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_refresh_leads:
				HashMap<String, String> user = sessionManager.getUserDetails();
				String empId = user.get(sessionManager.KEY_ID);
				AgileApplication.getInstance().spiceManager.execute(new LeadsJsonRequest(empId),
						JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new LeadListJsonRequestListener());
			break;

		case R.id.action_new_lead:
			Intent newLead = new Intent(getSherlockActivity(),NewLeadActivity.class);
			getSherlockActivity().startActivity(newLead);
		break;
		case android.R.id.home:
			getActivity().finish();
		break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
